<?php

namespace App\Http\Controllers;

use App\Lib\ApiResponse;
use App\Lib\WxMapHandle;
use App\Models\Staff;
use App\Repositories\WxMapRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class WxController extends Controller
{
    protected $repository;

    /**
     * @param WxMapRepository $repository
     */
    public function __construct(WxMapRepository $repository)
    {
        $this->repository = $repository;
    }

    public function wxQrcodeLogin(Request $request)
    {
        $key = $request->get('key');
        if(empty($key)){
            $key = uniqid(WxMapRepository::PC_LOGIN_STR.':');
            return redirect('/manage/login?key='.$key);
        }

        $result = $this->repository->getWxMapQrcode($key);
        if($result['status'] != ApiResponse::CODE_SUCCESS){
            abort(403, $result['message']);
        }

        $data = $result['data'];
        return view('manage.login',compact('data'));
    }

    public function checkWxQrcodeLogin(Request $request)
    {
        return $this->repository->checkWxQrcodeLogin($request);
    }

    public function wxQrcodeLoginSuccess(Request $request)
    {
        $token = $request->get('token');
        if(empty($token)){
            abort(403,'参数错误');
        }
        $staff = Staff::query()->where('login_token', $token)->first();
        if(empty($staff) || $staff->admin_type <= 0){
            abort(403,'管理员不存在,请联系总管理');
        }
        if(empty($staff->mall_id)){
            abort(403,'未分配租户,请联系总管理');
        }
        $staff->login_token = '';
        $staff->login_key = '';
        $staff->save();

        Auth::guard('admin')->login($staff);

        return redirect(route('reports'));
    }

    public function wxAuthLogin(Request $request,$mall_id)
    {
        $scene = $request->get('scene');
        switch ($scene){
            case WxMapRepository::FOOT_WORK_STR:
                $target_url = route('report.detail',$mall_id).'?rid='.$request->get('rid');
                break;
            case WxMapRepository::PC_LOGIN_STR:
                $request->session()->put('msg', '授权成功');
                $target_url = route('auth.success',$mall_id);
                break;
            default:
                $target_url = $request->session()->get('target_url')?:url('/');
                break;
        }

        if(Auth::check()){
            return redirect($target_url);
        }

        $app = WxMapHandle::getOfficialAccount($mall_id);
        $request->session()->put('target_url',$target_url);
        return $app->oauth->scopes(['snsapi_userinfo'])->stateless()
            ->redirect(route('wx.authCallback',$mall_id));
    }

    public function wxAuthCallback(Request $request,$mall_id)
    {
        $app = WxMapHandle::getOfficialAccount($mall_id);

        // 获取 OAuth 授权结果用户信息
        $wx_user = $app->oauth->user()->toArray();

        $user = $this->repository->saveWxUser($wx_user, $mall_id);
        $this->repository->syncWxUserInfoToStaff($user);
        $this->repository->syncWxUserInfoToReport($user);

        $target_url = $request->session()->get('target_url')??'/';
        $request->session()->forget('target_url');

        Auth::login($user);

        return redirect($target_url);
    }
}
